package org.eclipse.moquette.parser.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.eclipse.moquette.proto.messages.AbstractMessage;
import org.eclipse.moquette.proto.messages.UnsubscribeMessage;

/**
 * Created by alex on 15-5-26.
 */
public class UnsubscribeEncoder extends DemuxEncoder<UnsubscribeMessage> {

    @Override
    protected void encode(ChannelHandlerContext ctx, UnsubscribeMessage message, ByteBuf out) {

        if (message.topicFilters().isEmpty()) {
            throw new IllegalArgumentException("Found an unsubscribe message with empty topics");
        }

        if (message.getQos() != AbstractMessage.QOSType.LEAST_ONE) {
            throw new IllegalArgumentException("Expected a message with QOS 1, found " + message.getQos());
        }

        ByteBuf variableHeaderBuffer = ctx.alloc().buffer(4);
        ByteBuf buff = null;

        try {
            variableHeaderBuffer.writeShort(message.getMessageID());
            for (String topic : message.topicFilters()) {
                variableHeaderBuffer.writeBytes(Utils.encodeString(topic));
            }

            int variableHeaderSize = variableHeaderBuffer.readableBytes();
            byte flags = Utils.encodeFlags(message);
            buff = ctx.alloc().buffer(2 + variableHeaderSize);

            buff.writeByte(AbstractMessage.UNSUBSCRIBE << 4 | flags);
            buff.writeBytes(Utils.encodeRemainingLength(variableHeaderSize));
            buff.writeBytes(variableHeaderBuffer);

            out.writeBytes(buff);
        } finally {
            variableHeaderBuffer.release();
            buff.release();
        }

    }
}
